package main

import (
	"archive/zip"
	"flag"
	"fmt"
	"gitee.com/dreamwood/ez"
	"io"
	"os"
	"os/exec"
	path2 "path"
	"path/filepath"
	"strings"
)

func main() {

	var version string
	var name string
	var root string
	var nodir string
	var noext string
	flag.StringVar(&version, "v", "1.0", "版本号")
	flag.StringVar(&name, "name", "pack", "打包名")
	flag.StringVar(&root, "root", "./", "存放目录")
	flag.StringVar(&nodir, "nodir", ".git:.idea:.svn", "排除目录，单个值：dir,多个值dir1:dir2")
	flag.StringVar(&noext, "noext", "go:exe:exe~:zip:mod:sum:md:bat:ini", "排除后缀，单个值：ext1,多个值ext1:ext2")
	flag.Parse()
	dir, e := os.Getwd()
	if e != nil {
		println("os.Getwd()", e.Error())
	}

	e = ez.Copy("./config/app.ini", "./config/app.ini.back")
	if ez.PrintError(e) {
		return
	}

	//创建zip文件
	file, e := os.Create(fmt.Sprintf("%s%s_%s.zip", root, name, version))
	ez.PrintError(e)
	zipWriter := zip.NewWriter(file)
	defer zipWriter.Close()

	// 遍历当前文件夹下的目录，将所有的目录添加但监听列表
	e = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}
		//根目录的文件不打包
		if !strings.Contains(path[len(dir)+1:], "\\") {
			return nil
		}

		dirs := strings.Split(nodir, ":")
		for _, nodir := range dirs {
			if strings.HasPrefix(path, fmt.Sprintf(`%s\%s`, dir, nodir)) || strings.Contains(path, fmt.Sprintf(`\%s\`, nodir)) {
				return nil
			}
		}
		exts := strings.Split(noext, ":")
		for _, noext := range exts {
			if path2.Ext(path) == "."+noext {
				return nil
			}
		}
		reader, e := os.Open(path)
		ez.PrintError(e)
		fileWriter, e := zipWriter.Create(path[len(dir)+1:])
		println("写入", path[len(dir)+1:])
		ez.PrintError(e)
		_, e = io.Copy(fileWriter, reader)
		ez.PrintError(e)
		return nil
	})
	ez.PrintError(e)

	e = ez.Copy("./app/app.go", "./cache/pack/app.go.org")
	if ez.PrintError(e) {
		return
	}
	e = ez.Copy("./cache/pack/app.go.pack", "./app/app.go")
	if ez.PrintError(e) {
		return
	}

	//build 项目
	cmd := exec.Command("go", "build", "main.go")
	e = cmd.Run()
	ez.PrintError(e)

	e = ez.Copy("./cache/pack/app.go.org", "./app/app.go")
	if ez.PrintError(e) {
		return
	}

	reader, e := os.Open("./main.exe")

	ez.PrintError(e)
	target := fmt.Sprintf("%s_%s.exe", name, version)
	fileWriter, e := zipWriter.Create(target)
	println("写入", target)
	ez.PrintError(e)
	_, e = io.Copy(fileWriter, reader)
	ez.PrintError(e)
}
